package com.cloudatum.utils;

import com.cloudatum.redis.RedisUtil;
import com.cloudatum.service.VerificationCodeService;
import com.cloudatum.util.SpringUtil;
import com.cloudatum.utils.Constants;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;
import java.util.Map;

/**
 * 加载现有的验证码
 * Created by Administrator on 2015/12/11.
 */
public class LoadVerificationListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        VerificationCodeService codeService = SpringUtil.getBean("verificationCodeService", VerificationCodeService.class);
        Jedis jedis = null;
        try {
            jedis = RedisUtil.getJedis();
            List<Map<String,String>> ls = codeService.getAllVerification();
            for (Map<String,String> map : ls){
                jedis.hmset(Constants.VERIFICATION_ENTITY+map.get("id"),map);
                jedis.sadd(Constants.VERIFICATION_ENTITYID_SET,map.get("id"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (null != jedis){
                RedisUtil.returnResource(jedis);
            }
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
